/* eslint-disable react-hooks/exhaustive-deps */
/* eslint-disable no-unused-vars */
import React, { useState, useEffect } from 'react';
import { Form, Button, Checkbox, Table, Spin, message } from 'antd';
import { ArrowLeftOutlined } from '@ant-design/icons';
import { useBoolean } from 'ahooks';
import { If } from 'babel-plugin-jsx-control-statements';
import Cookies from 'js-cookie';
import Collapse from '@/components/collapse';
import UserInfo from '@/components/form/userInfo';
import ParkingLotInfo from '@/components/form/parkingLotInfo';
import ParkingLotExtraInfo from '@/components/form/parkingLotExtraInfo';
import FileExtraInfo from '@/components/form/fileExtraInfo';
import Modal from '@/components/modal';
import RequestApi from '@/utils/request';
import BusinessType from '@/utils/BusinessType';
import css from './index.scss';

const Business = () => {
	const columns = [
		{
			title: '序号',
			dataIndex: 'id',
			ellipsis: true,
			width: 80,
		},
		{
			title: '类型',
			dataIndex: 'type',
			ellipsis: true,
		},
		{
			title: '名称',
			dataIndex: 'name',
			ellipsis: true,
			width: 300,
		},
		{
			title: '模板附件',
			dataIndex: 'path',
			ellipsis: true,
			render: (text) => {
				return <a href={text}>预览</a>;
			},
		},
	];
	const [data, setData] = useState();
	const [spin, { setTrue, setFalse }] = useBoolean(false);
	useEffect(() => {
		RequestApi.connection('get', 'recordedReferenceAttachments/getAll').then((response) => {
			setTrue();
			setData({ ...response });
			setFalse();
		});
	}, []);
	return (
		<div>
			<If condition={data !== undefined}>
				<Spin spinning={spin} tip="加载中...">
					<Table columns={columns} rowKey="id" dataSource={data.data.row} pagination="false" />
				</Spin>
			</If>
		</div>
	);
};

export default () => {
	const [form] = Form.useForm();
	const [visible, { setTrue, setFalse }] = useBoolean(false);
	const userId = Cookies.get('id');
	const ownerType = 0;
	const ownerId = 0;
	const onFinish = (values) => {
		console.log('Success:', values);
		const attachIds = [];
		// 处理经营管理者基本信息的文件上传数据
		if (values.propertyRight !== null && values.propertyRight !== undefined) {
			const formDataPropertyRight = new FormData();
			formDataPropertyRight.append('file', values.propertyRight.file);
			RequestApi.connection(
				'post',
				`oss/upload/${ownerType}/${ownerId}/${BusinessType.getPropertyRight()}`,
				formDataPropertyRight
			).then((response) => {
				attachIds.push(response.data.row.id);
				values.attachIds = attachIds;
			});
		}
		if (values.permissionRight !== null && values.permissionRight !== undefined) {
			const formDataPermissionRight = new FormData();
			formDataPermissionRight.append('file', values.permissionRight.file);
			RequestApi.connection(
				'post',
				`oss/upload/${ownerType}/${ownerId}/${BusinessType.getPermissionRight()}`,
				formDataPermissionRight
			).then((response) => {
				attachIds.push(response.data.row.id);
			});
		}
		if (values.recommendation !== null && values.recommendation !== undefined) {
			const formDataRecommendation = new FormData();
			formDataRecommendation.append('file', values.recommendation.file);
			RequestApi.connection(
				'post',
				`oss/upload/${ownerType}/${ownerId}/${BusinessType.getRecommendation()}`,
				formDataRecommendation
			).then((response) => {
				attachIds.push(response.data.row.id);
			});
		}

		// 处理停车场设施-基本信息的文件上传数据
		if (values.confirmationOfCompletion !== null && values.confirmationOfCompletion !== undefined) {
			const formDataConfirmationOfCompletion = new FormData();
			formDataConfirmationOfCompletion.append('file', values.confirmationOfCompletion.file);
			RequestApi.connection(
				'post',
				`oss/upload/${ownerType}/${ownerId}/${BusinessType.getConfirmationOfCompletion()}`,
				formDataConfirmationOfCompletion
			).then((response) => {
				attachIds.push(response.data.row.id);
			});
		}
		if (values.parkLotList !== null && values.parkLotList !== undefined) {
			const formDataParkLotList = new FormData();
			formDataParkLotList.append('file', values.parkLotList.file);
			RequestApi.connection(
				'post',
				`oss/upload/${ownerType}/${ownerId}/${BusinessType.getParkLotList()}`,
				formDataParkLotList
			).then((response) => {
				attachIds.push(response.data.row.id);
			});
		}
		if (values.chargePilesEvidentialMaterial !== null && values.chargePilesEvidentialMaterial !== undefined) {
			const formDataChargePilesEvidentialMaterial = new FormData();
			formDataChargePilesEvidentialMaterial.append('file', values.chargePilesEvidentialMaterial.file);
			RequestApi.connection(
				'post',
				`oss/upload/${ownerType}/${ownerId}/${BusinessType.getChargePilesEvidentialMaterial()}`,
				formDataChargePilesEvidentialMaterial
			).then((response) => {
				attachIds.push(response.data.row.id);
			});
		}

		// 处理停车场设施-基本信息的所在地区
		if (values.districtName !== null && values.districtName !== undefined) {
			let districtName = '';
			for (let i = 0; i < values.districtName.length; i += 1) {
				districtName += `${values.districtName[i]},`;
			}
			values.districtName = districtName;
		}

		// 处理停车场设施-基本信息的位置属性
		if (values.positionProperty !== null && values.positionProperty !== undefined) {
			let positionProperty = '';
			for (let i = 0; i < values.positionProperty.length; i += 1) {
				positionProperty += `${values.positionProperty[i]},`;
			}
			values.positionProperty = positionProperty;
		}

		// 停车场设施-附属设施多选框处理
		if (values.guideSystemType !== null && values.guideSystemType !== undefined) {
			let guideSystemType = '';
			for (let i = 0; i < values.guideSystemType.length; i += 1) {
				guideSystemType += `${values.guideSystemType[i]},`;
			}
			values.guideSystemType = guideSystemType;
		}
		if (values.solidParkType !== null && values.solidParkType !== undefined) {
			let solidParkType = '';
			for (let i = 0; i < values.solidParkType.length; i += 1) {
				solidParkType += `${values.solidParkType[i]},`;
			}
			values.solidParkType = solidParkType;
		}
		if (values.fireFighting !== null && values.fireFighting !== undefined) {
			let fireFighting = '';
			for (let i = 0; i < values.fireFighting.length; i += 1) {
				fireFighting += `${values.fireFighting[i]},`;
			}
			values.fireFighting = fireFighting;
		}
		if (values.intelligentElectricChargeSystem !== null && values.intelligentElectricChargeSystem !== undefined) {
			let intelligentElectricChargeSystem = '';
			for (let i = 0; i < values.intelligentElectricChargeSystem.length; i += 1) {
				intelligentElectricChargeSystem += `${values.intelligentElectricChargeSystem[i]},`;
			}
			values.intelligentElectricChargeSystem = intelligentElectricChargeSystem;
		}
		if (values.signage !== null && values.signage !== undefined) {
			let signage = '';
			for (let i = 0; i < values.signage.length; i += 1) {
				signage += `${values.signage[i]},`;
			}
			values.signage = signage;
		}

		// 处理相关附件的文件上传数据
		if (values.businessLicense !== null && values.businessLicense !== undefined) {
			const formDataBusinessLicense = new FormData();
			formDataBusinessLicense.append('file', values.businessLicense.file);
			RequestApi.connection(
				'post',
				`oss/upload/${ownerType}/${ownerId}/${BusinessType.getBusinessLicense()}`,
				formDataBusinessLicense
			).then((response) => {
				attachIds.push(response.data.row.id);
			});
		}
		if (values.trafficOrganisationChart !== null && values.trafficOrganisationChart !== undefined) {
			const formDataTrafficOrganisationChart = new FormData();
			formDataTrafficOrganisationChart.append('file', values.trafficOrganisationChart.file);
			RequestApi.connection(
				'post',
				`oss/upload/${ownerType}/${ownerId}/${BusinessType.getTrafficOrganizationChart()}`,
				formDataTrafficOrganisationChart
			).then((response) => {
				attachIds.push(response.data.row.id);
			});
		}
		if (values.parkLotSettingList !== null && values.parkLotSettingList !== undefined) {
			const formDataParkLotSettingList = new FormData();
			formDataParkLotSettingList.append('file', values.parkLotSettingList.file);
			RequestApi.connection(
				'post',
				`oss/upload/${ownerType}/${ownerId}/${BusinessType.getParkSettingList()}`,
				formDataParkLotSettingList
			).then((response) => {
				attachIds.push(response.data.row.id);
			});
		}
		if (values.serviceAndSafeSystem !== null && values.serviceAndSafeSystem !== undefined) {
			const formDataServiceAndSafeSystem = new FormData();
			formDataServiceAndSafeSystem.append('file', values.serviceAndSafeSystem.file);
			RequestApi.connection(
				'post',
				`oss/upload/${ownerType}/${ownerId}/${BusinessType.getServiceAndSafeSystem()}`,
				formDataServiceAndSafeSystem
			).then((response) => {
				attachIds.push(response.data.row.id);
			});
		}
		if (values.manageOperateMaintainProject !== null && values.manageOperateMaintainProject !== undefined) {
			const formDataManageOperateMaintainProject = new FormData();
			formDataManageOperateMaintainProject.append('file', values.manageOperateMaintainProject.file);
			RequestApi.connection(
				'post',
				`oss/upload/${ownerType}/${ownerId}/${BusinessType.getManageOpeateMaintainProject()}`,
				formDataManageOperateMaintainProject
			).then((response) => {
				attachIds.push(response.data.row.id);
			});
		}
		if (values.emergencyResponsePlan !== null && values.emergencyResponsePlan !== undefined) {
			const formDataEmergencyResponsePlan = new FormData();
			formDataEmergencyResponsePlan.append('file', values.emergencyResponsePlan.file);
			RequestApi.connection(
				'post',
				`oss/upload/${ownerType}/${ownerId}/${BusinessType.getEmergencyResponsePlan()}`,
				formDataEmergencyResponsePlan
			).then((response) => {
				attachIds.push(response.data.row.id);
			});
		}
		if (values.others !== null && values.others !== undefined) {
			const formDataOthers = new FormData();
			formDataOthers.append('file', values.others.file);
			RequestApi.connection(
				'post',
				`oss/upload/${ownerType}/${ownerId}/${BusinessType.getOthers()}`,
				formDataOthers
			).then((response) => {
				attachIds.push(response.data.row.id);
				message.success('所有文件上传成功，即将提交数据');
			});
		}
		values.userId = userId;
		RequestApi.connection('post', `parkLotRecordTask/submit/${userId}`, values)
			.then(() => {
				message.success('提交成功');
			})
			.catch(() => {
				message.error('提交失败');
			});
	};

	const onFinishFailed = (errorInfo) => {
		console.log('Failed:', errorInfo);
	};

	const onSave = () => {
		const values = form.getFieldsValue();
		console.log(values);
		const attachIds = [];
		// 处理经营管理者基本信息的文件上传数据
		if (values.propertyRight !== null && values.propertyRight !== undefined) {
			const formDataPropertyRight = new FormData();
			formDataPropertyRight.append('file', values.propertyRight.file);
			RequestApi.connection(
				'post',
				`oss/upload/${ownerType}/${ownerId}/${BusinessType.getPropertyRight()}`,
				formDataPropertyRight
			).then((response) => {
				attachIds.push(response.data.row.id);
				values.attachIds = attachIds;
			});
		}
		if (values.permissionRight !== null && values.permissionRight !== undefined) {
			const formDataPermissionRight = new FormData();
			formDataPermissionRight.append('file', values.permissionRight.file);
			RequestApi.connection(
				'post',
				`oss/upload/${ownerType}/${ownerId}/${BusinessType.getPermissionRight()}`,
				formDataPermissionRight
			).then((response) => {
				attachIds.push(response.data.row.id);
			});
		}
		if (values.recommendation !== null && values.recommendation !== undefined) {
			const formDataRecommendation = new FormData();
			formDataRecommendation.append('file', values.recommendation.file);
			RequestApi.connection(
				'post',
				`oss/upload/${ownerType}/${ownerId}/${BusinessType.getRecommendation()}`,
				formDataRecommendation
			).then((response) => {
				attachIds.push(response.data.row.id);
			});
		}

		// 处理停车场设施-基本信息的文件上传数据
		if (values.confirmationOfCompletion !== null && values.confirmationOfCompletion !== undefined) {
			const formDataConfirmationOfCompletion = new FormData();
			formDataConfirmationOfCompletion.append('file', values.confirmationOfCompletion.file);
			RequestApi.connection(
				'post',
				`oss/upload/${ownerType}/${ownerId}/${BusinessType.getConfirmationOfCompletion()}`,
				formDataConfirmationOfCompletion
			).then((response) => {
				attachIds.push(response.data.row.id);
			});
		}
		if (values.parkLotList !== null && values.parkLotList !== undefined) {
			const formDataParkLotList = new FormData();
			formDataParkLotList.append('file', values.parkLotList.file);
			RequestApi.connection(
				'post',
				`oss/upload/${ownerType}/${ownerId}/${BusinessType.getParkLotList()}`,
				formDataParkLotList
			).then((response) => {
				attachIds.push(response.data.row.id);
			});
		}
		if (values.chargePilesEvidentialMaterial !== null && values.chargePilesEvidentialMaterial !== undefined) {
			const formDataChargePilesEvidentialMaterial = new FormData();
			formDataChargePilesEvidentialMaterial.append('file', values.chargePilesEvidentialMaterial.file);
			RequestApi.connection(
				'post',
				`oss/upload/${ownerType}/${ownerId}/${BusinessType.getChargePilesEvidentialMaterial()}`,
				formDataChargePilesEvidentialMaterial
			).then((response) => {
				attachIds.push(response.data.row.id);
			});
		}

		// 处理停车场设施-基本信息的所在地区
		if (values.districtName !== null && values.districtName !== undefined) {
			let districtName = '';
			for (let i = 0; i < values.districtName.length; i += 1) {
				districtName += `${values.districtName[i]},`;
			}
			values.districtName = districtName;
		}

		// 处理停车场设施-基本信息的位置属性
		if (values.positionProperty !== null && values.positionProperty !== undefined) {
			let positionProperty = '';
			for (let i = 0; i < values.positionProperty.length; i += 1) {
				positionProperty += `${values.positionProperty[i]},`;
			}
			values.positionProperty = positionProperty;
		}

		// 停车场设施-附属设施多选框处理
		if (values.guideSystemType !== null && values.guideSystemType !== undefined) {
			let guideSystemType = '';
			for (let i = 0; i < values.guideSystemType.length; i += 1) {
				guideSystemType += `${values.guideSystemType[i]},`;
			}
			values.guideSystemType = guideSystemType;
		}
		if (values.solidParkType !== null && values.solidParkType !== undefined) {
			let solidParkType = '';
			for (let i = 0; i < values.solidParkType.length; i += 1) {
				solidParkType += `${values.solidParkType[i]},`;
			}
			values.solidParkType = solidParkType;
		}
		if (values.fireFighting !== null && values.fireFighting !== undefined) {
			let fireFighting = '';
			for (let i = 0; i < values.fireFighting.length; i += 1) {
				fireFighting += `${values.fireFighting[i]},`;
			}
			values.fireFighting = fireFighting;
		}
		if (values.intelligentElectricChargeSystem !== null && values.intelligentElectricChargeSystem !== undefined) {
			let intelligentElectricChargeSystem = '';
			for (let i = 0; i < values.intelligentElectricChargeSystem.length; i += 1) {
				intelligentElectricChargeSystem += `${values.intelligentElectricChargeSystem[i]},`;
			}
			values.intelligentElectricChargeSystem = intelligentElectricChargeSystem;
		}
		if (values.signage !== null && values.signage !== undefined) {
			let signage = '';
			for (let i = 0; i < values.signage.length; i += 1) {
				signage += `${values.signage[i]},`;
			}
			values.signage = signage;
		}

		// 处理相关附件的文件上传数据
		if (values.businessLicense !== null && values.businessLicense !== undefined) {
			const formDataBusinessLicense = new FormData();
			formDataBusinessLicense.append('file', values.businessLicense.file);
			RequestApi.connection(
				'post',
				`oss/upload/${ownerType}/${ownerId}/${BusinessType.getBusinessLicense()}`,
				formDataBusinessLicense
			).then((response) => {
				attachIds.push(response.data.row.id);
			});
		}
		if (values.trafficOrganisationChart !== null && values.trafficOrganisationChart !== undefined) {
			const formDataTrafficOrganisationChart = new FormData();
			formDataTrafficOrganisationChart.append('file', values.trafficOrganisationChart.file);
			RequestApi.connection(
				'post',
				`oss/upload/${ownerType}/${ownerId}/${BusinessType.getTrafficOrganizationChart()}`,
				formDataTrafficOrganisationChart
			).then((response) => {
				attachIds.push(response.data.row.id);
			});
		}
		if (values.parkLotSettingList !== null && values.parkLotSettingList !== undefined) {
			const formDataParkLotSettingList = new FormData();
			formDataParkLotSettingList.append('file', values.parkLotSettingList.file);
			RequestApi.connection(
				'post',
				`oss/upload/${ownerType}/${ownerId}/${BusinessType.getParkSettingList()}`,
				formDataParkLotSettingList
			).then((response) => {
				attachIds.push(response.data.row.id);
			});
		}
		if (values.serviceAndSafeSystem !== null && values.serviceAndSafeSystem !== undefined) {
			const formDataServiceAndSafeSystem = new FormData();
			formDataServiceAndSafeSystem.append('file', values.serviceAndSafeSystem.file);
			RequestApi.connection(
				'post',
				`oss/upload/${ownerType}/${ownerId}/${BusinessType.getServiceAndSafeSystem()}`,
				formDataServiceAndSafeSystem
			).then((response) => {
				attachIds.push(response.data.row.id);
			});
		}
		if (values.manageOperateMaintainProject !== null && values.manageOperateMaintainProject !== undefined) {
			const formDataManageOperateMaintainProject = new FormData();
			formDataManageOperateMaintainProject.append('file', values.manageOperateMaintainProject.file);
			RequestApi.connection(
				'post',
				`oss/upload/${ownerType}/${ownerId}/${BusinessType.getManageOpeateMaintainProject()}`,
				formDataManageOperateMaintainProject
			).then((response) => {
				attachIds.push(response.data.row.id);
			});
		}
		if (values.emergencyResponsePlan !== null && values.emergencyResponsePlan !== undefined) {
			const formDataEmergencyResponsePlan = new FormData();
			formDataEmergencyResponsePlan.append('file', values.emergencyResponsePlan.file);
			RequestApi.connection(
				'post',
				`oss/upload/${ownerType}/${ownerId}/${BusinessType.getEmergencyResponsePlan()}`,
				formDataEmergencyResponsePlan
			).then((response) => {
				attachIds.push(response.data.row.id);
			});
		}
		if (values.others !== null && values.others !== undefined) {
			const formDataOthers = new FormData();
			formDataOthers.append('file', values.others.file);
			RequestApi.connection(
				'post',
				`oss/upload/${ownerType}/${ownerId}/${BusinessType.getOthers()}`,
				formDataOthers
			).then((response) => {
				attachIds.push(response.data.row.id);
			});
		}
		values.attachIds = attachIds;
		values.userId = userId;
		console.log('values: ', values);
		RequestApi.connection('post', `parkLotRecordTask/hold/${userId}`, values)
			.then(() => {
				message.success('暂存成功');
			})
			.catch(() => {
				message.error('暂存失败,可能是数据为填写完！！');
			});
	};

	// 控制是否可以提交表单
	function isRead(value) {
		const result = value.target.checked;
		if (result === true) {
			document.getElementById('isSubmit').disabled = false;
		} else if (result === false) {
			document.getElementById('isSubmit').disabled = true;
		}
	}
	function result(v1, v2) {
		console.log(v1, v2);
		form.setFieldsValue({
			entranceLongitude: v1,
			entranceLatitude: v2,
		});
	}
	return (
		<div className={css.app}>
			<div className={css.header}>
				<span className={css.back_myRecord}>
					<ArrowLeftOutlined />
				</span>
				<span>我的备案</span>
				<Button type="link" onClick={() => setTrue()}>
					<span className={css.download}>备案申请模板下载</span>
				</Button>
				<Modal title="备案申请模板下载" visible={visible} onOk={() => setTrue()} onCancel={() => setFalse()}>
					<Business />
				</Modal>
				<span className={css.tip}>特别提醒: 由于上传资料过多，填写过程请及时暂存,以免上传失效重复填写。</span>
			</div>
			<div className={css.content}>
				<Form name="parkLotSubmitDTO" form={form} layout="vertical" onFinish={onFinish} onFinishFailed={onFinishFailed}>
					<Collapse
						form1={<UserInfo form={form} />}
						form2={<ParkingLotInfo result={result} form={form} />}
						form3={<ParkingLotExtraInfo />}
						form4={<FileExtraInfo />}
					/>
					<Form.Item wrapperCol={{ offset: 8, span: 16 }} className={css.submit}>
						<Form.Item name="remember" valuePropName="checked" noStyle>
							<Checkbox onChange={isRead}>
								<span style={{ color: '#2882fe' }}>我已认真阅读并同意以上条款</span>
							</Checkbox>
						</Form.Item>
						<Button type="primary" onClick={onSave}>
							暂存
						</Button>
						<Button type="primary" htmlType="submit" disabled id="isSubmit">
							提交
						</Button>
					</Form.Item>
				</Form>
			</div>
		</div>
	);
};
